package com.sjc.algorithm.interview;

import java.util.Stack;

/**
 * 返回栈最小的值
 * @author by SangJiacun
 * @Date 2020/5/13 22:02
 */
public class MinStack {

    private Stack<Integer> mainStack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();

    public static void main(String[] args) throws Exception {
        MinStack stack = new MinStack();

        stack.push(4);
        stack.push(9);
        stack.push(7);
        stack.push(8);
        stack.push(1);
        stack.push(3);
        stack.push(5);

        System.out.println(stack.getMin());
        stack.pop();
        stack.pop();
        stack.pop();
        System.out.println(stack.getMin());
        stack.pop();
        stack.pop();
        stack.pop();
        System.out.println(stack.getMin());

    }

    private void push(int element){
        mainStack.push(element);
        if(minStack.empty() || element <= minStack.peek()){
            minStack.push(element);
        }
    }

    private Integer pop(){
        if(mainStack.peek().equals(minStack.peek())){
            minStack.pop();
        }
        return mainStack.pop();
    }

    private Integer getMin() throws Exception {
        if(minStack.empty()){
            throw new Exception("最小栈为空");
        }
        return minStack.peek();
    }
}
